<?php

/**
 *  Display one emedia item
 *
 * @copyright (c) 2012 University of Geneva
 * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
 * @author Laurent Opprecht laurent@opprecht.info
 */
require('../../config.php');
require_once("$CFG->dirroot/mod/emedia/lib/emedia.class.php");
require_once("$CFG->dirroot/mod/emedia/lib/emedia_view.class.php");
require_once("$CFG->dirroot/mod/emedia/lib/emedia_store.class.php");
require_once($CFG->libdir . '/completionlib.php');

$id = optional_param('id', 0, PARAM_INT);        // Course module ID
$u = optional_param('u', 0, PARAM_INT);          // emedia instance id
$redirect = optional_param('redirect', 0, PARAM_BOOL);

// Two ways to specify the module
if ($u)
{
    $emedia = EMediaStore::select_by_id($u);
    $cm = get_coursemodule_from_instance('emedia', $emedia->id, $emedia->course, false, MUST_EXIST);
}
else
{
    $cm = get_coursemodule_from_id('emedia', $id, 0, false, MUST_EXIST);
    $emedia = EMediaStore::select_by_cm($cm);
}

$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);

require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/emedia:view', $context);

add_to_log($course->id, 'emedia', 'view', 'view.php?id=' . $cm->id, $emedia->id, $cm->id);

// Update 'viewed' state if required by completion system
$completion = new completion_info($course);
$completion->set_module_viewed($cm);

$PAGE->set_url('/mod/emedia/view.php', array('id' => $cm->id));

EMediaView::create($course, $cm, $emedia)->display();
